from django.db import models
from django.core import validators
from django.db.models import F
from django.utils.timezone import now
from ckeditor_uploader.fields import RichTextUploadingField
from decimal import Decimal
from accounts.models import User,Address

# Create your models here.

class MoneyField(models.DecimalField):
    def __init__(self,verbose_name=None,name=None,max_digits=8,decimal_places=2,**kwargs):
        kwargs.setdefault('default',Decimal('0').quantize(Decimal(0.00)))
        kwargs.setdefault('validators',[validators.MinValueValidator(0)] )
        super().__init__(verbose_name=None,name=None,max_digits=8,decimal_places=2,**kwargs)

class Category(models.Model):
    title=models.CharField('分类名称',max_length=50)
    class Meta:
        verbose_name='分类'
        verbose_name_plural=verbose_name

    def __str__(self):
        return self.title

class Product(models.Model):
    GENDER_CHOICES=((1,'男士'),(2,'女士'))
    TYPE_CHOICES=((1,'上装'),(2,'下装'),(3,'鞋子'))
    CATEGORY_CHOICES=((1,'毛衣'),(2,'卫衣'),(3,'T恤'))

    title=models.CharField('商品名称',max_length=200,db_index=True)
    price=MoneyField('价格')
    sales_price=MoneyField('销售价格')
    discount=models.IntegerField('折扣比例',default=100,help_text='填写1-100,50表示5折',
                                 validators=[validators.MinValueValidator(1),validators.MaxValueValidator(100)])

    size=models.CharField('尺码',max_length=200)

    gender=models.IntegerField('性别',choices=GENDER_CHOICES,db_index=True)
    type=models.IntegerField('类型',choices=TYPE_CHOICES,db_index=True)
    category=models.ForeignKey(Category,verbose_name='分类')
    content=RichTextUploadingField('商品详情', null=True, blank=True)
    stock=models.IntegerField('库存',default=0,validators=[validators.MinValueValidator(0)])
    class Meta:
        verbose_name='商品'
        verbose_name_plural=verbose_name
    def __str__(self):
        return self.title

    def save(self, *args,**kwargs):
        if self.sales_price<1:
            self.sales_price=self.price
        self.discount=self.sales_price / self.price *100
        if self.discount<1:
            self.discount=100
        return super().save(*args,**kwargs)

class ProductStyle(models.Model):
    product=models.ForeignKey(Product,verbose_name='商品',related_name='style')
    title=models.CharField('款式标题',max_length=200)
    img=models.ImageField('款式图片',)
    class Meta:
        verbose_name='款式'
        verbose_name_plural=verbose_name

    def __str__(self):
        return f'{self.product.title}-{self.title}'

class ProductPic(models.Model):
    product = models.ForeignKey(Product, verbose_name='商品', related_name='pic')
    title = models.CharField('款式标题', max_length=200)
    img = models.ImageField('图片', )
    class Meta:
        verbose_name='商品图片'
        verbose_name_plural=verbose_name

    def __str__(self):
        return f'Pic：{self.product.title}-{self.title}'

class ShopCart(models.Model):
    user=models.ForeignKey(User)
    product=models.ForeignKey(Product)
    style=models.ForeignKey(ProductStyle)
    size=models.CharField('尺码',max_length=20)
    count=models.IntegerField('数量',default=1)
    checked=models.BooleanField('是否选中',default=False)
    class Meta:
        unique_together=(('user','product','style','size',),)

class ShopOrder(models.Model):
    STATUS_CHOICES={(1,'已签收'),(2,'未签收')}
    user = models.ForeignKey(User)
    addr =models.ForeignKey(Address)
    status=models.IntegerField('订单状态',choices=STATUS_CHOICES,default=2)
    amount=MoneyField('订单金额')
    pay_amount=MoneyField('付款金额')
class ShopItem(models.Model):
    order=models.ForeignKey(ShopOrder,verbose_name='购物车条目')
    style = models.ForeignKey(ProductStyle,verbose_name='款式')
    size = models.CharField('尺码', max_length=20)
    count = models.IntegerField('数量', default=1)
    price=MoneyField('售价')

class Voucher(models.Model):
    user=models.ForeignKey(User)
    amount=MoneyField('代金券金额')
    description=models.CharField('来源及用途',max_length=200)
    used=models.BooleanField('是否使用',default=False)
    over_datetime=models.DateTimeField('过期时间',blank=True,null=True)
    over_id=models.IntegerField('订单号',default=0)

    def can_use(self):
        if self.used:
            return False
        if self.over_datetime and now()>self.over_datetime:
            return False
        return True

    def use(self,order):
        self.order_id=order.id
        self.used=True
        self.save()

        order.pay_amount = models.F('amount')-self.amount
        order.save()
        order.refresh_from_db()
        return order


